package cn.renxuan.service.weather;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

import com.fasterxml.jackson.core.type.TypeReference;

import cn.renxuan.entity.FS_DomesticWeather;
import cn.renxuan.enums.EWeatherDataSource;
import cn.renxuan.http.HttpUtil;
import cn.renxuan.http.constant.HttpHeader;
import cn.renxuan.service.weather.json.BaiduApiBase;
import cn.renxuan.service.weather.json.BaiduWeather;
import cn.renxuan.service.weather.json.LunDearBase;
import cn.renxuan.service.weather.json.LunDearWeather;
import cn.renxuan.service.weather.mapper.BaiduWeatherMapper;

public class BaiduWeatherService implements IWeatherService {
    public BaiduWeatherService() {
        // Constructor logic if needed
    }

    @Override
    public FS_DomesticWeather getDomesticWeather(Map<String, String> querys, Map<String, String> headers)
            throws Exception {
        FS_DomesticWeather retVal = null;

        WeatherConfig weatherConfig = WeatherHelper.getWeatherConfigByPropName("baidu-map-configKey");
        LocalDateTime now = LocalDateTime.now();
        BaiduApiBase<BaiduWeather> baiduWeather = null;
        if (headers == null) {
            headers = new HashMap<String, String>();
        }
        headers.put(HttpHeader.HTTP_HEADER_CONTENT_TYPE, "application/json; charset=utf-8");

        // 从网络获取天气数据
        baiduWeather = HttpUtil
                .<BaiduApiBase<BaiduWeather>>getAndResTxt(new TypeReference<BaiduApiBase<BaiduWeather>>() {
                },
                        weatherConfig.getBasepath(),
                        weatherConfig.getRealapiurl(), 5000,
                        headers,
                        querys);
        if (baiduWeather != null && "0".equals(baiduWeather.getStatus())) {
            retVal = BaiduWeatherMapper.INSTANCE.toDomesticWeather(baiduWeather);
            if (retVal != null) {
                retVal.setDatasource((byte) EWeatherDataSource.Baidu.ordinal());
                retVal.setCitycode(retVal.getCountycode().substring(0, 4));
                retVal.setProvincecode(retVal.getCountycode().substring(0, 2));
                retVal.setYear((short) now.getYear());
                retVal.setMonth((byte) now.getMonth().getValue());
                retVal.setDay((byte) now.getDayOfMonth());
                retVal.setHour((byte) now.getHour());
                retVal.setMinute((byte) now.getMinute());
                retVal.setSecond((byte) now.getSecond());
                retVal.setCreationtime(now);
                retVal.setIsdeleted(false);
                retVal.setRestxt(baiduWeather.getRestxt());
            }
        }
        return retVal;
    }

}
